//
// Created by TongHua on 2020/12/21.
//

#ifndef WEBSERVER_PROCESSPOOL_HPP
#define WEBSERVER_PROCESSPOOL_HPP

#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <assert.h>
#include <stdio.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <fcntl.h>
#include <stdlib.h>
#include <sys/epoll.h>
#include <signal.h>
#include <sys/wait.h>
#include <sys/stat.h>

/**
 * @brief 进程对象
 *
 */
class Process
{
public:
    Process() : m_pid(-1) {}
public:
    pid_t m_pid;        // 进程编号
    int m_pipefd[2];     // 通信管道
};

/**
 * @brief 进程池
 *
 * @tparam T 用户对象
 */
template <typename T>
class ProcessPool
{
private:
    /**
     * @brief Construct a new Process Pool object
     *
     * @param _listenfd 监听描述符
     * @param _process_number 进程池管理的进程数量
     */
    ProcessPool(int _listenfd,int _process_number = 8);
public:
    /**
     * @brief 单例，创建唯一的进程池对象
     *
     * @param _listenfd
     * @param _process_number
     * @return ProcessPool<T>*
     */
    static ProcessPool<T>* Create(int _listenfd,int _process_number = 1)
    {
        if(!m_instance)
        {
            m_instance = new ProcessPool<T> (_listenfd,_process_number);
        }
        return m_instance;
    }
    /**
     * @brief 执行进程池
     *
     */
    void Run();
    ~ProcessPool()
    {
        delete[] m_sub_process;
    }
private:
    /**
     * @brief 设置信号
     *
     */
    void SetupSigPipe();
    /**
     * @brief 执行父进程方法
     *
     */
    void RunParent();
    /**
     * @brief 执行子进程方法
     *
     */
    void RunChild();
private:
    Process* m_sub_process;                 // 所有的进程对象
    static ProcessPool<T>* m_instance;      // 进程池实例
    static const int MAX_PROCESS_NUM = 16;  // 最大进程数量
    static const int MAX_USER_NUM_PER_PROCESS = 65535;  // 每个子进程拥有的最大客户数量
    static const int MAX_EVENT_NUM = 10000; // EPOLL最大处理事件数
    int m_process_num;                      // 进程数量
    int m_idx;                              // 进程编号（针对子进程）
    int m_epollfd;                          // 每个子进程中的epoll
    int m_listenfd;
    int m_stop;                             // 进程是否停止
private:
};

template <typename T>
ProcessPool<T>* ProcessPool<T>::m_instance = NULL;

static int m_sig_pipefd[2];                    // 信号通信管道

/**
 * @brief Set the Noblocking object
 *
 * @param _fd 文件描述符
 * @return int 返回修改前的文件描述符状态
 */
static int SetNoblocking(int _fd)
{
    int old_option = fcntl( _fd, F_GETFL );
    int new_option = old_option | O_NONBLOCK;
    fcntl( _fd, F_SETFL, new_option );
    return old_option;
}

/**
 * @brief 向epoll中添加对文件描述符的监听
 *
 * @param _epollfd
 * @param _fd
 */
static void Addfd(int _epollfd,int _fd)
{
    epoll_event event;
    event.data.fd = _fd;
    event.events = EPOLLIN | EPOLLET;
    epoll_ctl( _epollfd, EPOLL_CTL_ADD, _fd, &event );
    SetNoblocking( _fd );
}

/**
 * @brief 从epoll中移除监听并且关闭文件描述符
 *
 * @param _epollfd
 * @param _fd
 */
static void Removefd(int _epollfd,int _fd)
{
    epoll_ctl(_epollfd,EPOLL_CTL_DEL,_fd,0);
    close(_fd);
}

/*!
 * 信号处理函数
 * @param _sig 信号
 */
static void sig_handler(int _sig)
{
    int save_errno = errno;
    int msg = _sig;
    send(m_sig_pipefd[1],(char*)&msg,1,0);
    errno = save_errno;
}

/**
 * @brief 添加信号处理函数
 *
 * @param _sig
 * @param handler
 * @param restart 重启系统调用，用于针对慢速系统调用不用返回EINTR错误而是重新启动
 */
static void AddSignal(int _sig,void (handler)(int),bool restart = true)
{
    struct sigaction sa;
    memset( &sa, '\0', sizeof( sa ) );
    sa.sa_handler = handler;
    if( restart )
    {
        sa.sa_flags |= SA_RESTART;
    }
    sigfillset( &sa.sa_mask );
    assert( sigaction( _sig, &sa, NULL ) != -1 );
}

template<typename T>
ProcessPool<T>::ProcessPool(int _listenfd,int _process_number)
        : m_listenfd(_listenfd),m_process_num(_process_number),m_idx(-1),m_stop(false)
{
    assert((m_process_num>0) && (m_process_num <= MAX_PROCESS_NUM));

    // 创建线程队列
    m_sub_process = new Process[m_process_num];
    assert(m_sub_process);

    for(int i=0;i<m_process_num;++i)
    {
        int ret = socketpair(PF_UNIX,SOCK_STREAM,0,m_sub_process[i].m_pipefd);
        assert(ret == 0);

        m_sub_process[i].m_pid = fork();
        assert(m_sub_process[i].m_pid >= 0);
        if(m_sub_process[i].m_pid > 0)  // 父进程
        {
            close(m_sub_process[i].m_pipefd[1]);
            continue;
        }else{
            close(m_sub_process[i].m_pipefd[0]);
            m_idx = i;
            break;  // 子进程不需要进行创建工作，直接退出
        }
    }
}

template<typename T>
void ProcessPool<T>::SetupSigPipe()
{
    // epoll监听信号和管道
    m_epollfd = epoll_create(5);
    assert(m_epollfd != -1);

    // 信号管道，用于统一事件源
    int ret = socketpair(PF_UNIX,SOCK_STREAM,0,m_sig_pipefd);
    assert(ret != -1);

    SetNoblocking(m_sig_pipefd[1]);
    Addfd(m_epollfd,m_sig_pipefd[0]);

    AddSignal( SIGCHLD, sig_handler );
    AddSignal( SIGTERM, sig_handler );
    AddSignal( SIGINT, sig_handler );
    AddSignal( SIGPIPE, SIG_IGN );
}

template<typename T>
void ProcessPool<T>::Run()
{
    // 执行进程池
    // 对于父进程 m_idx = -1
    // 对于子进程 m_idx >= 0
    if(m_idx != -1)
    {
        RunChild();
        return;
    }
    RunParent();
}

template<typename T>
void ProcessPool<T>::RunChild()
{
    SetupSigPipe();
    printf("执行子进程\n");

    int pipefd = m_sub_process[m_idx].m_pipefd[1];  // 读取父进程传递的消息
    Addfd(m_epollfd,pipefd);

    epoll_event events[MAX_EVENT_NUM];
    T* users = new T [MAX_USER_NUM_PER_PROCESS];
    assert(users);
    int number = 0;
    int ret = -1;

    while(!m_stop)
    {
        number = epoll_wait(m_epollfd,events,MAX_EVENT_NUM,-1);
        if((number < 0) && (errno != EINTR))
        {
            printf("Epoll failure!\n");
            break;
        }
        for(int i=0;i<number;++i)
        {
            int sockfd = events[i].data.fd;
            if((sockfd == pipefd) && (events[i].events & EPOLLIN)) // 父进程通知子进程有新客户端连接
            {
                int client = 0;
                ret = recv(sockfd,(char*)&client,sizeof(client),0);
                if((ret < 0) && (errno != EAGAIN) || ret == 0)
                {
                    continue;   // 读取错误
                }else
                {
                    // 如果接受成功，那么就对接受新客户端的连接
                    sockaddr_in client_address;
                    socklen_t client_length = sizeof(client_address);
                    int connfd = accept(m_listenfd,(sockaddr*)&client_address,&client_length);
                    if(connfd < 0)
                    {
                        printf("accept errno = [%d]\n",errno);
                        continue;
                    }
                    Addfd(m_epollfd,connfd);
                    // 需要实现init方法
                    users[connfd].init(m_epollfd,connfd,client_address);
                    // 打印新客户端连接提示
                    printf("a new client connect success\n");
                }
            }else if((sockfd == m_sig_pipefd[0]) && (events[i].events & EPOLLIN))
            {
                int sig;
                char signals[1024];
                ret = recv(m_sig_pipefd[0],signals,sizeof(signals),0);
                if(ret < 0)
                {
                    continue;
                }else{
                    for(int i=0;i<ret;++i)
                    {
                        switch(signals[i])
                        {
                            case SIGCHLD:
                                pid_t pid;
                                int stat;
                                while((pid = waitpid(-1,&stat,WNOHANG)) > 0)
                                {
                                    continue;
                                }
                                break;
                            case SIGTERM:
                            case SIGINT:
                                m_stop = true;
                                break;
                            default:
                                break;
                        }
                    }
                }
            }else if(events[i].events & EPOLLIN)    // 其他可读事件
            {
                users[sockfd].process();
            }else
            {
                continue;
            }
        }
    }
    delete[] users;
    users = NULL;
    close(pipefd);
    close(m_epollfd);
}

template<typename T>
void ProcessPool<T>::RunParent()
{
    SetupSigPipe();

    Addfd(m_epollfd,m_listenfd);

    epoll_event events[MAX_EVENT_NUM];
    int sub_process_counter = 0;    // 工作进程数量
    int new_conn = 1;
    int number = 0;
    int ret = -1;

    while(!m_stop)
    {
        number = epoll_wait(m_epollfd,events,MAX_EVENT_NUM,-1);
        if((number < 0) && (errno != EINTR))
        {
            printf("Epoll failure\n");
            break;
        }
        for ( int i = 0; i < number; i++ )
        {
            int sockfd = events[i].data.fd;
            if(sockfd == m_listenfd)
            {
                int i = sub_process_counter;
                do
                {
                    if(m_sub_process[i].m_pid != -1)    // 进程有效
                    {
                        break;
                    }
                    i = (i+1) % m_process_num;          // 轮询下一个进程
                }while(i != sub_process_counter);

                if(m_sub_process[i].m_pid == -1)        // 进程池中无可用的进程
                {
                    m_stop = true;
                    break;
                }
                sub_process_counter = (i+1) % m_process_num;    // 指向下一个进程
                send(m_sub_process[i].m_pipefd[0],(char*)&new_conn,sizeof(new_conn),0);
                printf("send request to child process [%d] with pid is [%d]\n",i,m_sub_process[i].m_pid);
            }else if ((sockfd == m_sig_pipefd[0]) && (events[i].events & EPOLLIN))
            {
                int sig;
                char signals[1024];
                ret = recv(m_sig_pipefd[0],signals,sizeof(signals),0);
                if(ret < 0)
                {
                    continue;
                }else
                {
                    for(size_t i=0;i<ret;++i)
                    {
                        switch(signals[i])
                        {
                            case SIGCHLD:
                                pid_t pid;
                                int stat;
                                while((pid = waitpid(-1,&stat,WNOHANG)) > 0)
                                {
                                    for(int i=0;i<m_process_num;++i)
                                    {
                                        if(m_sub_process[i].m_pid == pid)
                                        {
                                            printf("child process [%d] exit\n",i);
                                            close(m_sub_process[i].m_pipefd[0]);
                                            m_sub_process[i].m_pid = -1;    // 标记进程已关闭
                                        }
                                    }
                                }
                                m_stop = true;
                                for(int i=0;i<m_process_num;++i)
                                {
                                    if(m_sub_process[i].m_pid != -1)
                                    {
                                        m_stop = false;
                                        break;
                                    }
                                }
                                break;
                            case SIGTERM:
                            case SIGINT:
                                printf("kill all child process\n");
                                for( int i = 0; i < m_process_num; ++i )
                                {
                                    int pid = m_sub_process[i].m_pid;
                                    if(pid!=-1)
                                    {
                                        printf("发送kill信号\n");
                                        kill(pid,SIGTERM);  // TODO
                                    }
                                }
                                break;
                            default:
                                break;
                        }
                    }
                }
            }else
            {
                continue;
            }
        }
    }
    close(m_epollfd);
}
#endif //WEBSERVER_PROCESSPOOL_HPP
